'use server'

import {cookies} from "next/headers";

export async function handleRefresh() {
    const refreshToken = await getRefreshToken();
    try {
        const token = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}/api/auth/token/refresh/`,
            {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({refresh: refreshToken})
            })
        const data = await token.json();

        if (data.access) {
            cookies().set('session_access_token', data.access, {
                httpOnly: false,
                secure: false,
                maxAge: 60 * 60,
                path: '/'
            });

            return data.access;
        }

        return token;

    } catch (err) {
        console.error('refresh ACHTUNG!!!', err);
    }
}

export async function handleLogin(userId: string, accessToken: string, refreshToken: string) {
    cookies().set('session_userid', userId, {
        httpOnly: false,
        secure: false,
        maxAge: 60 * 60 * 24 * 7,
        path: '/'
    });

    cookies().set('Iloged', '1', {
        httpOnly: false,
        secure: false,
        maxAge: 60 * 60 * 24 * 7,
        path: '/'
    });

    cookies().set('session_access_token', accessToken, {
        httpOnly: false,
        secure: false,
        maxAge: 60 * 60,
        path: '/'
    });

    cookies().set('session_refresh_token', refreshToken, {
        httpOnly: false,
        secure: false,
        maxAge: 60 * 60 * 24 * 7,
        path: '/'
    });
}

export async function resetAuthCookies() {
    cookies().delete('session_userid');
    cookies().delete('Iloged');
    cookies().delete('session_access_token');
    cookies().delete('session_refresh_token');
}

export async function getUserId() {
    const userId = cookies().get('session_userid')?.value
    return userId ? userId : null
}

export async function getAccessToken() {
    let accessToken = cookies().get('session_access_token')?.value;

    if (!accessToken) {
        accessToken = await handleRefresh();
    }

    return accessToken;
}

export async function getRefreshToken() {
    return cookies().get('session_refresh_token')?.value;
}
